<template>
  <v-card>
    <v-card-title class="align-start flex p-5">
      <sdao1 />
      <v-spacer />
      <div>
        <v-menu activator="parent" bottom offset-y>
          <template #activator="{ on, attrs }">
            <span v-bind="attrs" v-on="on">
              <v-icon color="#736B7D">mdi-dots-vertical</v-icon>
            </span>
          </template>

          <v-list class="bg-white reward-more-list">
            <v-list-item @click="handleShowAccountInfo(true)">
              <v-list-item-title>账号</v-list-item-title>
            </v-list-item>
          </v-list>
        </v-menu>
      </div>
    </v-card-title>

    <v-card-text class="text-no-wrap text--primary">
      <p class="font-semibold text-sm mb-1 text-[#736B7D]">
        {{ statTitle }}
      </p>

      <div class="d-flex align-end flex-wrap">
        <span class="font-semibold text-2xl mb-3 text-[#736B7D]">
          {{ token }}
        </span>
      </div>
      <div class="flex align-center justify-between">
        <div>
          <v-chip
            v-if="chipColor && chipColor !== ''"
            small
            :color="chipColor"
            class="v-chip-light-bg font-semibold text-[#8B8D92] text-[16px]"
            :class="`${chipColor}--text`"
            :disabled="withdrawBtnDisabled"
            @click.stop="withdraw"
          >
            {{ subtitle }}
          </v-chip>
          <v-avatar color="#F2EAFF" class="v-avatar-light-bg ml-2" size="20">
            <span class="text-sm text-[#9255FD]">?</span>

            <v-tooltip activator="parent" location="top">
              {{ t('message.dashboard.reward.tooltip') }}
            </v-tooltip>
          </v-avatar>
        </div>
        <v-chip
          v-if="dailyColor && dailyColor !== ''"
          small
          :color="dailyColor"
          class="v-chip-light-bg font-semibold text-[#8B8D92] text-[16px]"
          :class="`${dailyColor}--text`"
          :disabled="withdrawBtnDisabled"
          @click.stop="handleSignReward"
        >
        Claim Daily Reward
        </v-chip>
      </div>
    </v-card-text>
  </v-card>

  <v-dialog
    persistent
    class="account-info-dialog"
    v-model="dialog"
    max-width="688px"
  >
    <v-card class="bg-white p-5 m-6">
      <div
        class="
          dialog-header
          text-[#736b7d]
          font-medium
          flex
          justify-between
          pb-9
        "
      >
        <span class="title text-xl">账户</span>
        <v-icon
          color="gray darken-2"
          class="text-gray-400"
          @click.stop="handleShowAccountInfo(false)"
        >
          mdi-close
        </v-icon>
      </div>
      <div class="content text-[#736b7d] text-sm font-medium leading-5">
        <div class="part pb-2">
          <div v-for="key in infoKeys" :key="key" :class="[key]">
            <span class="label">{{ infoLabelData[key] }}：</span>
            <span v-if="key === 'level'">
              <v-img
                :width="24"
                :src="`/src/icons/level/level_${infoData.level}.svg`"
                cover
              ></v-img>
            </span>
            <span v-else class="value">{{ infoData[key] }}</span>
          </div>
        </div>
        <div class="part pb-2 pt-2">
          <p>您总共获得了 {{ total }} SDAO奖励。</p>
        </div>
        <div class="part pb-2 pt-2">
          <div v-for="key in rewardKeys" :key="key" class="item">
            <span class="label">{{ rewardLabelData[key] }}：</span>
            <span class="value">{{ rewardData[key] }}</span>
          </div>
        </div>
        <div class="part pt-2">
          <span class="label">可用余额：</span>
          <span class="value">{{ balance }} SDAO</span>
        </div>
      </div>
    </v-card>
  </v-dialog>
  <SignRewardDialog :visible='visible' :infoData="dialogData" @close='showDialog'/>
</template>

<script lang="ts" setup>
import { inject, onBeforeMount, reactive, ref, toRefs, watch } from 'vue';

import sdao1 from '@/icons/sdao1.svg?component';
import Dialog from '@/components/dialog/dialog';
import WalletStore from '@/store/WalletStore';
import useContractHook from '@/hooks/Contract';
import { MULTICALL_ADDRESS, MULTICALL_ABI } from '@/utils/constants';
import { preWithdrawApi, withdrawApi,dAccountInfoApi, getAccountDetail } from '@/api/dashboard';
import { useI18n } from 'vue-i18n';
import { signRewardApi } from '@/api/home.ts'
import UserStore from '@/store/UserStore';
import SignRewardDialog from '@/components/SignRewardDialog.vue'

interface RewardProps {
  token: number;
}

const props = withDefaults(defineProps<RewardProps>(), {
  token: 0,
});

const { token } = toRefs(props);
console.log('reward token:', token.value);

const { t } = useI18n();

const rewardOptions = {
  statTitle: t('message.dashboard.reward.title'),
  color: 'info',
  subtitle: t('message.dashboard.reward.withdraw'),
  chipColor: '#9155fd',
  dailyBtnText: t('message.dashboard.reward.withdraw'),
  dailyColor: '#2B6EEF',
};

const { statTitle, subtitle, chipColor, dailyBtnText, dailyColor } =
  rewardOptions;

const walletStore = WalletStore();

const useContract = useContractHook();

const userStore = UserStore();

const emitter = inject('emitter');

const withdrawLoading = ref<boolean>(false);
const withdrawBtnDisabled = ref<boolean>(false);
const withdraw = () => {
  console.log('wallet address:', walletStore.walletAddress);
  console.log('withdraw provider:', walletStore.provider);
  withdrawBtnDisabled.value = true;
  withdrawLoading.value = true;
  if (walletStore.walletAddress === undefined) {
    Dialog(t('message.dashboard.reward.connect'));
    withdrawBtnDisabled.value = false;
    withdrawLoading.value = false;
    return;
  }
  if (walletStore.provider === undefined) {
    Dialog(t('message.dashboard.reward.connect'));
    withdrawBtnDisabled.value = false;
    withdrawLoading.value = false;
    return;
  }

  if (token.value === 0) {
    Dialog(t('message.dashboard.reward.insufficient'));
    withdrawBtnDisabled.value = false;
    withdrawLoading.value = false;
    return;
  }

  // 提现
  preWithdrawApi()
    .then(async (res: any) => {
  
      const amount = res.amount;

      const tractionHash = await useContract.withdraw(
        MULTICALL_ADDRESS,
        MULTICALL_ABI,
        res.text
      );

      console.log('tractionHash:', tractionHash);

      if (tractionHash === null) {
        withdrawBtnDisabled.value = false;
        return;
      }

      withdrawApi({
        amount: amount,
        txid: tractionHash,
      })
        .then((res: any) => {
          console.log('withdrawApi res:', res);
          // @ts-ignore
          emitter.emit('refreshReward');
          Dialog(t('message.dashboard.reward.success'),1000);
          withdrawLoading.value = false;
          withdrawBtnDisabled.value = false;
          dAccountInfoApi().then((result: any) => {
            token.value = result.balance;
          });
        })
        .catch((err: any) => {
          // Dialog('withdraw error')
          console.log('preWithdrawApi err:', err);
          const { message } = err;
          Dialog(message);
          withdrawLoading.value = false;
          withdrawBtnDisabled.value = false;
        });
    })
    .catch((err: any) => {
      // Dialog('withdraw error')
      console.log('preWithdrawApi err:', err);
      const { message } = err.data || err;
      Dialog(message);
      withdrawLoading.value = false;
      withdrawBtnDisabled.value = false;
    });
};

const dialog = ref<boolean>(false);

const handleShowAccountInfo = visible => {
  if (walletStore.walletAddress === undefined) {
    Dialog(t('message.dashboard.reward.connect'));
    return;
  }
  if (walletStore.provider === undefined) {
    Dialog(t('message.dashboard.reward.connect'));
    return;
  }
  dialog.value = visible;
};

let infoKeys = ['wallet', 'level', 'address', 'DC', 'TG', 'belong', 'time'];
let rewardKeys = ['day', 'recommend', 'activity', 'withdraw'];

let infoLabelData = {
  wallet: '钱包',
  level: '等级',
  address: '推荐人地址',
  DC: '推荐人DC',
  TG: '推荐人TG',
  belong: '隶属于',
  time: '上次领奖时间',
};
let rewardLabelData = {
  day: '每日奖励',
  recommend: '推荐奖励',
  activity: '活动奖励',
  withdraw: '体现总额',
};

let state = reactive({
  infoData: {
    wallet: '--',
    level: '--',
    address: '--',
    DC: '--',
    TG: '--',
    belong: '--',
    time: '--',
  },
  total: '--',
  rewardData: {
    day: '--',
    recommend: '--',
    activity: '--',
    withdraw: '--',
  },
  balance: '--',
  visible: false,
  dialogData: null,
  signRewardBtn: false,
});

let { infoData, total, rewardData, balance, visible, dialogData } = toRefs(state);

let showDialog = (visible) => {
  state.visible = visible
}

let handleSignReward = () => {
  if(state.signRewardBtn) return
  state.signRewardBtn = true
  signRewardApi()
  .then(({data}) => {
    state.dialogData = data
    showDialog(true)
    state.signRewardBtn = false
  })
  .catch(() => {
    state.signRewardBtn = false
  })
}

let getAccountData = () => {
  console.log('>>>>>>>>>>>>>>')
  getAccountDetail()
  .then((data) => {
    let { shareCode, level, uplineCode, uplineDc, uplineTg, organize, lastSignTime, totalReward, signReward, recommendReward, activityReward, withdrawAmount, balance } = data
    state.infoData = {
      wallet: shareCode,
      level: level,
      address: uplineCode,
      DC: uplineDc,
      TG: uplineTg,
      belong: organize,
      time: lastSignTime,
    }
    state.total = totalReward
    state.rewardData = {
      day: signReward,
      recommend: recommendReward,
      activity: activityReward,
      withdraw: withdrawAmount,
    }
    state.balance = balance
  })
}

watch( () => userStore.token, () => {
  getAccountData()
})

onBeforeMount(()=> {
  if(userStore.token) getAccountData()
})
</script>

<style lang="scss" scoped>
.percentage {
  top: -8px;
  position: relative;
}
</style>
<style lang="scss">
.reward-more-list {
  padding: 5px 0;
  .v-list-item {
    padding: 5px 0;
    min-height: 20px;
    cursor: pointer;
    .v-list-item-title {
      color: #736b7d;
      font-size: 14px;
    }
  }
}

.account-info-dialog {
  .v-overlay__content {
    width: 100%;
  }
  .content {
    .part:not(:nth-last-child(1)) {
      border-bottom: 1px solid #d8d8d8;
      .DC,
      .TG {
        .value {
          color: #174de5;
        }
      }
      .level{
        display: flex;
        align-items: center;
      }
    }
  }
}
</style>
